<template>
  <div>
    <canvas ref="canvas" id="canvas" style="width: 500px; height: 500px" />
  </div>
</template>

<script setup lang="ts">
import {
  BlinnPhongMaterial,
  Camera,
  Color,
  DirectLight,
  MeshRenderer,
  PrimitiveMesh,
  Vector3,
  WebGLEngine,
} from 'oasis-engine'
import { OrbitControl } from 'oasis-engine-toolkit'
const {
  // creRootNode,
  // creCamera,
  // creLightEntity,
  // creCubeEntity,
  openRun,
  rootEntity,
  camera,
  directLight,
} = oasisApi()

const canvas = ref(null)
const engine = ref(null) as any
function oasisApi() {
  const rootEntity = ref(null) as any
  const camera = ref(null) as any
  const directLight = ref(null) as any
  // 创建根节点
  const creRootNode = () => {
    const scene = engine.value.sceneManager.activeScene
    rootEntity.value = scene.createRootEntity('root')
  }
  // 创建相机
  const creCamera = () => {
    let cameraEntity = rootEntity.value.createChild('camera_entity')
    cameraEntity.transform.position = new Vector3(0, 5, 10)
    cameraEntity.transform.lookAt(new Vector3(0, 0, 0))
    camera.value = cameraEntity.addComponent(Camera)
    cameraEntity.transform.setPosition(3, 3, 3)
    cameraEntity.addComponent(OrbitControl)
  }
  // 拉起光源
  const creLightEntity = () => {
    let lightEntity = rootEntity.value.createChild('light')

    directLight.value = lightEntity.addComponent(DirectLight)
    directLight.value.color = new Color(1.0, 1.0, 1.0)
    directLight.value.intensity = 0.5

    lightEntity.transform.rotation = new Vector3(45, 45, 45)
  }
  // 创建立方体/鸭子
  const creCubeEntity = () => {
    // let cubeEntity = rootEntity.value.createChild('cube')
    // let cube = cubeEntity.addComponent(MeshRenderer)
    // cube.mesh = PrimitiveMesh.createCuboid(engine.value, 0.5, 0.3, 0.3)
    // cube.setMaterial(new BlinnPhongMaterial(engine.value))

    engine.value.resourceManager
      .load(
        'https://gw.alipayobjects.com/os/OasisHub/267000040/9994/%25E5%25BD%2592%25E6%25A1%25A3.gltf',
      )
      .then(gltf => {
        rootEntity.value.addChild(gltf.defaultSceneRoot)
      })
  }

  const openRun = () => {
    creRootNode()
    creCamera()
    creLightEntity()
    creCubeEntity()
    engine.value.run()
  }

  return {
    creRootNode,
    creCamera,
    creLightEntity,
    creCubeEntity,
    openRun,
    rootEntity,
    camera,
    directLight,
  }
}

onMounted(async () => {
  // 初始化引擎
  engine.value = new WebGLEngine('canvas')
  // 根据页面设置 canvas 大小
  engine.value.canvas.resizeByClientSize()

  openRun()
})
</script>
